import React, { useState, useEffect } from 'react';
import Sidebar from '../../components/sidebar';
import defaultAvatar from '../../static/defaultAvatar.png';
import axios from 'axios';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';

// 预设固定的设备ID列表
const FIXED_DEVICE_IDS = [1, 2, 3, 4, 5]; // 根据实际需求修改此数组

const EnvData = () => {
    const [envData, setEnvData] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [selectedDeviceId, setSelectedDeviceId] = useState(null); // 默认选择全部设备
    const [chartData, setChartData] = useState([]);
    const [timeRange, setTimeRange] = useState('day'); // 'day', 'week', 'month'
    const [skip, setSkip] = useState(0);
    const [limit] = useState(100); // 删除 setLimit
    const [totalCount, setTotalCount] = useState(0);
    const [startTime, setStartTime] = useState('');
    const [endTime, setEndTime] = useState('');
    const [dateFilterType, setDateFilterType] = useState('range'); // 'range', 'timeRange'
    const [envThresholds, setEnvThresholds] = useState([]); // 环境阈值数据
    const [selectedPlantType, setSelectedPlantType] = useState('兰花'); // 默认选择兰花
    const [isAddModalOpen, setIsAddModalOpen] = useState(false); // 控制添加数据模态框显示
    const [formData, setFormData] = useState({
        id: '',
        record_time: '',
        device_id: 1,
        air_temp: 0,
        air_humidity: 0,
        co2: 0,
        soil_temp: 0,
        soil_humidity: 0,
        soil_ph: 0,
        nitrogen: 0,
        phosphorus: 0,
        potassium: 0
    });
    const [submitStatus, setSubmitStatus] = useState({
        loading: false,
        success: false,
        error: ''
    });

    // 页面加载时获取环境数据和阈值数据
    useEffect(() => {
        fetchEnvData();
        fetchEnvThresholds();
    }, []);

    // 当筛选条件变化时，重置分页并获取数据
    useEffect(() => {
        setSkip(0);
    }, [selectedDeviceId, dateFilterType, startTime, endTime, timeRange]);

    // 当分页或筛选条件变化时，更新数据
    useEffect(() => {
        fetchEnvData();
    }, [skip, limit, selectedDeviceId, startTime, endTime]);

    // 当设备ID或时间范围变化时，更新图表数据
    useEffect(() => {
        updateChartData();
    }, [envData, selectedDeviceId]);

    // 获取环境数据
    const fetchEnvData = async () => {
        setLoading(true);
        setError('');
        try {
            // 构建查询参数
            let queryParams = `skip=${skip}&limit=${limit}`;

            if (selectedDeviceId !== null && selectedDeviceId !== undefined) {
                queryParams += `&device_id=${selectedDeviceId}`;
            }

            if (dateFilterType === 'range') {
                if (startTime) queryParams += `&start_time=${startTime}`;
                if (endTime) queryParams += `&end_time=${endTime}`;
            } else {
                const now = new Date();
                let startDate;
                if (timeRange === 'day') {
                    startDate = new Date(now);
                    startDate.setDate(now.getDate() - 1);
                } else if (timeRange === 'week') {
                    startDate = new Date(now);
                    startDate.setDate(now.getDate() - 7);
                } else if (timeRange === 'month') {
                    startDate = new Date(now);
                    startDate.setMonth(now.getMonth() - 1);
                }

                if (startDate) {
                    queryParams += `&start_time=${startDate.toISOString()}`;
                    queryParams += `&end_time=${now.toISOString()}`;
                }
            }

            const response = await axios.get(
                `http://zxhp-dev.keepnuts.top/api/v1/env-data/?${queryParams}`,
                {
                    headers: {
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTI3MjkxNzgsInN1YiI6IjNiZDhiMzlmLWQ2MWItNDVlMi04NDEyLWZiZjM5ZmQ4MTRiYSJ9.jLYeph_gNnOBdESbb_EUbFw71unNuqL2ZoBl7rmVhZ8'
                    }
                }
            );
            console.log('环境数据响应:', response.data);

            // 过滤掉值全为0的数据点（可能是无效数据）
            const filteredData = response.data.filter(item => {
                return item.air_humidity !== 0 ||
                    item.air_temp !== 0 ||
                    item.soil_humidity !== 0 ||
                    item.soil_temp !== 0 ||
                    item.soil_ph !== 0 ||
                    item.nitrogen !== 0 ||
                    item.phosphorus !== 0 ||
                    item.potassium !== 0 ||
                    item.co2 !== 0;
            });

            setEnvData(filteredData);
            setTotalCount(filteredData.length); // 修正为过滤后的数据长度

        } catch (err) {
            setError('获取环境数据失败，请检查网络或重试');
            console.error('请求错误:', err);
        } finally {
            setLoading(false);
        }
    };

    // 获取环境阈值数据
    const fetchEnvThresholds = async () => {
        try {
            const response = await axios.get(
                'http://zxhp-dev.keepnuts.top/api/v1/env-data/thresholds',
                {
                    headers: {
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTI3MjkxNzgsInN1YiI6IjNiZDhiMzlmLWQ2MWItNDVlMi04NDEyLWZiZjM5ZmQ4MTRiYSJ9.jLYeph_gNnOBdESbb_EUbFw71unNuqL2ZoBl7rmVhZ8'
                    }
                }
            );
            console.log('环境阈值响应:', response.data);
            const uniqueThresholds = [...new Map(response.data.map(item => [item.id, item])).values()];
            setEnvThresholds(uniqueThresholds);
        } catch (err) {
            console.error('获取环境阈值失败:', err);
        }
    };

    // 创建环境记录数据
    const createEnvData = async () => {
        setSubmitStatus({ ...submitStatus, loading: true, error: '' });

        try {
            // 生成UUID作为id
            const uuid = self.crypto.randomUUID();

            // 准备提交数据
            const submitData = {
                ...formData,
                id: uuid,
                // 确保record_time是ISO格式
                record_time: formData.record_time ? new Date(formData.record_time).toISOString() : new Date().toISOString()
            };

            const response = await axios.post(
                'http://zxhp-dev.keepnuts.top/api/v1/env-data/',
                submitData,
                {
                    headers: {
                        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTI3MjkxNzgsInN1YiI6IjNiZDhiMzlmLWQ2MWItNDVlMi04NDEyLWZiZjM5ZmQ4MTRiYSJ9.jLYeph_gNnOBdESbb_EUbFw71unNuqL2ZoBl7rmVhZ8',
                        'Content-Type': 'application/json'
                    }
                }
            );

            console.log('创建环境数据成功:', response.data);
            setSubmitStatus({ loading: false, success: true, error: '' });

            // 关闭模态框并刷新数据
            setTimeout(() => {
                setIsAddModalOpen(false);
                fetchEnvData(); // 重新获取数据
                resetForm(); // 重置表单
            }, 1500);

        } catch (err) {
            console.error('创建环境数据失败:', err);
            const errorMsg = err.response?.data?.message || '创建环境数据失败，请重试';
            setSubmitStatus({ loading: false, success: false, error: errorMsg });
        }
    };

    // 获取当前选中植物类型的阈值
    const getCurrentThresholds = () => {
        return envThresholds.find(item => item.plant_type === selectedPlantType) || {};
    };

    // 检查环境数据是否在阈值范围内
    const isValueInRange = (value, min, max) => {
        return value >= min && value <= max;
    };

    // 更新图表数据
    const updateChartData = () => {
        if (envData.length === 0) return;

        // 如果选择全部设备，则计算所有设备的平均值
        let deviceData;
        if (selectedDeviceId === null) {
            // 按时间分组计算平均值
            const timeGroups = {};
            envData.forEach(item => {
                const time = item.record_time;
                if (!timeGroups[time]) {
                    timeGroups[time] = {
                        count: 0,
                        air_temp: 0,
                        air_humidity: 0,
                        soil_temp: 0,
                        soil_humidity: 0,
                        soil_ph: 0,
                        co2: 0,
                        nitrogen: 0,
                        phosphorus: 0,
                        potassium: 0
                    };
                }
                timeGroups[time].count++;
                timeGroups[time].air_temp += item.air_temp;
                timeGroups[time].air_humidity += item.air_humidity;
                timeGroups[time].soil_temp += item.soil_temp;
                timeGroups[time].soil_humidity += item.soil_humidity;
                timeGroups[time].soil_ph += item.soil_ph;
                timeGroups[time].co2 += item.co2;
                timeGroups[time].nitrogen += item.nitrogen;
                timeGroups[time].phosphorus += item.phosphorus;
                timeGroups[time].potassium += item.potassium;
            });

            // 计算平均值
            deviceData = Object.keys(timeGroups).map(time => {
                const group = timeGroups[time];
                return {
                    record_time: time,
                    air_temp: group.air_temp / group.count,
                    air_humidity: group.air_humidity / group.count,
                    soil_temp: group.soil_temp / group.count,
                    soil_humidity: group.soil_humidity / group.count,
                    soil_ph: group.soil_ph / group.count,
                    co2: group.co2 / group.count,
                    nitrogen: group.nitrogen / group.count,
                    phosphorus: group.phosphorus / group.count,
                    potassium: group.potassium / group.count
                };
            });
        } else {
            // 筛选所选设备的数据
            deviceData = envData.filter(item => item.device_id === selectedDeviceId);
        }

        // 按时间排序
        const sortedData = [...deviceData].sort((a, b) =>
            new Date(a.record_time) - new Date(b.record_time)
        );

        // 为图表准备数据
        const chartReadyData = sortedData.map(item => ({
            time: formatDateTime(item.record_time),
            airTemp: item.air_temp,
            airHumidity: item.air_humidity,
            soilTemp: item.soil_temp,
            soilHumidity: item.soil_humidity,
            soilPh: item.soil_ph,
            co2: item.co2,
            nitrogen: item.nitrogen,
            phosphorus: item.phosphorus,
            potassium: item.potassium
        }));

        setChartData(chartReadyData);
    };

    // 格式化日期时间
    const formatDateTime = (dateTimeStr) => {
        const date = new Date(dateTimeStr);
        return date.toLocaleString();
    };

    // 处理设备选择变化
    const handleDeviceChange = (e) => {
        setSelectedDeviceId(e.target.value === '' ? null : Number(e.target.value));
    };

    // 处理植物类型选择变化
    const handlePlantTypeChange = (e) => {
        setSelectedPlantType(e.target.value);
    };

    // 处理时间范围选择
    const handleTimeRangeChange = (range) => {
        setTimeRange(range);
        setDateFilterType('timeRange');
    };

    // 处理开始日期变化
    const handleStartTimeChange = (e) => {
        setStartTime(e.target.value);
        setDateFilterType('range');
    };

    // 处理结束日期变化
    const handleEndTimeChange = (e) => {
        setEndTime(e.target.value);
        setDateFilterType('range');
    };

    // 处理分页
    const goToPrevPage = () => {
        if (skip > 0) {
            setSkip(skip - limit);
        }
    };

    const goToNextPage = () => {
        if ((skip + limit) < totalCount) {
            setSkip(skip + limit);
        }
    };

    // 处理表单输入变化
    const handleFormChange = (e) => {
        const { name, value } = e.target;
        setFormData(prev => {
            if (name === 'device_id') {
                return { ...prev, [name]: Number(value) };
            } else if ([
                'air_temp', 'air_humidity', 'co2', 'soil_temp', 'soil_humidity', 'soil_ph', 'nitrogen', 'phosphorus', 'potassium'
            ].includes(name)) {
                return { ...prev, [name]: value === '' ? '' : parseFloat(value) };
            } else {
                return { ...prev, [name]: value };
            }
        });
    };

    // 处理记录时间变化
    const handleRecordTimeChange = (e) => {
        setFormData(prev => ({
            ...prev,
            record_time: e.target.value
        }));
    };

    // 重置表单
    const resetForm = () => {
        setFormData({
            id: '',
            record_time: '',
            device_id: 1,
            air_temp: 0,
            air_humidity: 0,
            co2: 0,
            soil_temp: 0,
            soil_humidity: 0,
            soil_ph: 0,
            nitrogen: 0,
            phosphorus: 0,
            potassium: 0
        });
        setSubmitStatus({
            loading: false,
            success: false,
            error: ''
        });
    };

    // 打开添加数据模态框
    const openAddModal = () => {
        resetForm();
        setIsAddModalOpen(true);
    };

    // 关闭添加数据模态框
    const closeAddModal = () => {
        setIsAddModalOpen(false);
        // 重置提交状态
        setTimeout(resetForm, 300);
    };

    return (
        <div className="flex h-screen">
            <Sidebar />
            <div className="flex-1 flex flex-col">
                <header className="flex justify-between items-center p-4 bg-white shadow">
                    <h1 className="text-xl font-semibold">环境数据监控</h1>
                    <div className="flex items-center">
                        <span className="mr-2">用户名</span>
                        <img className='w-10 h-10 rounded-full border-black border-2' src={defaultAvatar} />
                    </div>
                </header>

                <div className="flex-1 p-6 overflow-y-auto">
                    {/* 筛选条件和添加按钮 */}
                    <div className="bg-white p-4 rounded-lg mb-6 shadow-sm">
                        <div className="flex flex-wrap gap-4 items-center justify-between">
                            <div className="flex flex-wrap gap-4">
                                <div className="flex items-center">
                                    <label htmlFor="deviceSelect" className="mr-2 text-sm font-medium text-gray-700">设备:</label>
                                    <select
                                        id="deviceSelect"
                                        value={selectedDeviceId !== null ? selectedDeviceId.toString() : ''}
                                        onChange={handleDeviceChange}
                                        className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    >
                                        <option value="">全部设备</option>
                                        {FIXED_DEVICE_IDS.map(deviceId => (
                                            <option key={deviceId} value={deviceId}>
                                                设备 {deviceId}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div className="flex items-center">
                                    <label htmlFor="plantTypeSelect" className="mr-2 text-sm font-medium text-gray-700">植物类型:</label>
                                    <select
                                        id="plantTypeSelect"
                                        value={selectedPlantType}
                                        onChange={handlePlantTypeChange}
                                        className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    >
                                        {Array.from(new Set(envThresholds.map(item => item.plant_type))).map(plantType => (
                                            <option key={plantType} value={plantType}>
                                                {plantType}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                {/* 时间范围选择器 */}
                                <div className="flex items-center">
                                    <label className="mr-2 text-sm font-medium text-gray-700">时间范围:</label>
                                    <div className="flex space-x-2">
                                        <button
                                            className={`px-3 py-1 rounded-md text-sm ${timeRange === 'day' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'}`}
                                            onClick={() => handleTimeRangeChange('day')}
                                        >
                                            日
                                        </button>
                                        <button
                                            className={`px-3 py-1 rounded-md text-sm ${timeRange === 'week' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'}`}
                                            onClick={() => handleTimeRangeChange('week')}
                                        >
                                            周
                                        </button>
                                        <button
                                            className={`px-3 py-1 rounded-md text-sm ${timeRange === 'month' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700'}`}
                                            onClick={() => handleTimeRangeChange('month')}
                                        >
                                            月
                                        </button>
                                    </div>
                                </div>

                                {/* 自定义日期范围选择器 */}
                                <div className="flex items-center">
                                    <label htmlFor="startTime" className="mr-2 text-sm font-medium text-gray-700">开始日期:</label>
                                    <input
                                        type="datetime-local"
                                        id="startTime"
                                        value={startTime}
                                        onChange={handleStartTimeChange}
                                        className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                </div>

                                <div className="flex items-center">
                                    <label htmlFor="endTime" className="mr-2 text-sm font-medium text-gray-700">结束日期:</label>
                                    <input
                                        type="datetime-local"
                                        id="endTime"
                                        value={endTime}
                                        onChange={handleEndTimeChange}
                                        className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                </div>
                            </div>

                            {/* 添加数据按钮 */}
                            <button
                                onClick={openAddModal}
                                className="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500"
                            >
                                <i className="fas fa-plus mr-1"></i> 添加环境记录
                            </button>
                        </div>
                    </div>

                    {/* 当前阈值显示 */}
                    {envThresholds.length > 0 && (
                        <div className="bg-white p-4 rounded-lg mb-6 shadow-sm">
                            <h3 className="text-lg font-medium text-gray-900 mb-4">
                                {selectedPlantType} 环境参数阈值
                            </h3>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">空气温度</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().air_temp_min}°C - {getCurrentThresholds().air_temp_max}°C
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">空气湿度</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().air_humidity_min}% - {getCurrentThresholds().air_humidity_max}%
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">土壤温度</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().soil_temp_min}°C - {getCurrentThresholds().soil_temp_max}°C
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">土壤湿度</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().soil_humidity_min}% - {getCurrentThresholds().soil_humidity_max}%
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">土壤pH值</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().soil_ph_min} - {getCurrentThresholds().soil_ph_max}
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">CO2浓度</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().co2_min}ppm - {getCurrentThresholds().co2_max}ppm
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">氮含量</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().nitrogen_min} - {getCurrentThresholds().nitrogen_max}
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">磷含量</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().phosphorus_min} - {getCurrentThresholds().phosphorus_max}
                                    </p>
                                </div>
                                <div className="bg-gray-50 p-3 rounded-lg">
                                    <p className="text-sm text-gray-500">钾含量</p>
                                    <p className="text-lg font-medium">
                                        {getCurrentThresholds().potassium_min} - {getCurrentThresholds().potassium_max}
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 加载和错误提示 */}
                    {loading && (
                        <div className="flex items-center justify-center py-12">
                            <div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"></div>
                            <span className="ml-3 text-gray-500">加载中...</span>
                        </div>
                    )}

                    {error && (
                        <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
                            <div className="flex">
                                <div className="flex-shrink-0">
                                    <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                                    </svg>
                                </div>
                                <div className="ml-3">
                                    <p className="text-sm text-red-700">{error}</p>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 数据概览卡片 */}
                    {envData.length > 0 && (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
                            {/* 空气温度卡片 */}
                            <div className="bg-white p-4 rounded-lg shadow-sm">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-500">空气温度</p>
                                        <p className={`text-2xl font-semibold mt-1 ${!isValueInRange(
                                            envData.reduce((sum, item) => sum + item.air_temp, 0) / envData.length,
                                            getCurrentThresholds().air_temp_min,
                                            getCurrentThresholds().air_temp_max
                                        ) ? 'text-red-500' : 'text-gray-900'
                                            }`}>
                                            {Math.round(envData.reduce((sum, item) => sum + item.air_temp, 0) / envData.length)}°C
                                        </p>
                                    </div>
                                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                                        <i className="fas fa-thermometer-half text-blue-500"></i>
                                    </div>
                                </div>
                            </div>

                            {/* 空气湿度卡片 */}
                            <div className="bg-white p-4 rounded-lg shadow-sm">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-500">空气湿度</p>
                                        <p className={`text-2xl font-semibold mt-1 ${!isValueInRange(
                                            envData.reduce((sum, item) => sum + item.air_humidity, 0) / envData.length,
                                            getCurrentThresholds().air_humidity_min,
                                            getCurrentThresholds().air_humidity_max
                                        ) ? 'text-red-500' : 'text-gray-900'
                                            }`}>
                                            {Math.round(envData.reduce((sum, item) => sum + item.air_humidity, 0) / envData.length)}%
                                        </p>
                                    </div>
                                    <div className="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center">
                                        <i className="fas fa-tint text-blue-500"></i>
                                    </div>
                                </div>
                            </div>

                            {/* 土壤温度卡片 */}
                            <div className="bg-white p-4 rounded-lg shadow-sm">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-500">土壤温度</p>
                                        <p className={`text-2xl font-semibold mt-1 ${!isValueInRange(
                                            envData.reduce((sum, item) => sum + item.soil_temp, 0) / envData.length,
                                            getCurrentThresholds().soil_temp_min,
                                            getCurrentThresholds().soil_temp_max
                                        ) ? 'text-red-500' : 'text-gray-900'
                                            }`}>
                                            {Math.round(envData.reduce((sum, item) => sum + item.soil_temp, 0) / envData.length)}°C
                                        </p>
                                    </div>
                                    <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                                        <i className="fas fa-seedling text-green-500"></i>
                                    </div>
                                </div>
                            </div>

                            {/* 土壤湿度卡片 */}
                            <div className="bg-white p-4 rounded-lg shadow-sm">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-500">土壤湿度</p>
                                        <p className={`text-2xl font-semibold mt-1 ${!isValueInRange(
                                            envData.reduce((sum, item) => sum + item.soil_humidity, 0) / envData.length,
                                            getCurrentThresholds().soil_humidity_min,
                                            getCurrentThresholds().soil_humidity_max
                                        ) ? 'text-red-500' : 'text-gray-900'
                                            }`}>
                                            {Math.round(envData.reduce((sum, item) => sum + item.soil_humidity, 0) / envData.length)}%
                                        </p>
                                    </div>
                                    <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center">
                                        <i className="fas fa-water text-green-500"></i>
                                    </div>
                                </div>
                            </div>

                            {/* CO2浓度卡片 */}
                            <div className="bg-white p-4 rounded-lg shadow-sm">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-sm text-gray-500">CO2浓度</p>
                                        <p className={`text-2xl font-semibold mt-1 ${!isValueInRange(
                                            envData.reduce((sum, item) => sum + item.co2, 0) / envData.length,
                                            getCurrentThresholds().co2_min,
                                            getCurrentThresholds().co2_max
                                        ) ? 'text-red-500' : 'text-gray-900'
                                            }`}>
                                            {Math.round(envData.reduce((sum, item) => sum + item.co2, 0) / envData.length)}ppm
                                        </p>
                                    </div>
                                    <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center">
                                        <i className="fas fa-cloud text-gray-500"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 图表区域 */}
                    {chartData.length > 0 && (
                        <div className="bg-white p-4 rounded-lg shadow-sm mb-6">
                            <h3 className="text-lg font-medium text-gray-900 mb-4">
                                {selectedDeviceId !== null ? `设备 ${selectedDeviceId} 环境数据趋势` : '所有设备环境数据趋势'}
                            </h3>
                            <div className="h-[300px]">
                                <ResponsiveContainer width="100%" height="100%">
                                    <BarChart data={chartData}>
                                        <CartesianGrid strokeDasharray="3 3" />
                                        <XAxis dataKey="time" tick={{ fontSize: 10 }} tickCount={5} />
                                        <YAxis />
                                        <Tooltip />
                                        <Legend />
                                        <Bar dataKey="airTemp" fill="#8884d8" name="空气温度(°C)" />
                                        <Bar dataKey="airHumidity" fill="#82ca9d" name="空气湿度(%)" />
                                        <Bar dataKey="soilTemp" fill="#ffc658" name="土壤温度(°C)" />
                                        <Bar dataKey="soilHumidity" fill="#ff9800" name="土壤湿度(%)" />
                                    </BarChart>
                                </ResponsiveContainer>
                            </div>
                        </div>
                    )}

                    {/* 数据表格 */}
                    <div className="bg-white rounded-lg shadow-sm overflow-hidden">
                        <div className="px-4 py-3 border-b border-gray-200">
                            <h3 className="text-lg font-medium text-gray-900">
                                {selectedDeviceId !== null ? `设备 ${selectedDeviceId} 环境数据列表` : '所有设备环境数据列表'}
                            </h3>
                            <p className="text-sm text-gray-500">共 {totalCount} 条记录</p>
                        </div>
                        <div className="overflow-x-auto">
                            <table className="min-w-full divide-y divide-gray-200">
                                <thead className="bg-gray-50">
                                    <tr>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            记录时间
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            设备ID
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            空气温度(°C)
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            空气湿度(%)
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            土壤温度(°C)
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            土壤湿度(%)
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            土壤pH
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            CO2(ppm)
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            氮含量
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            磷含量
                                        </th>
                                        <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                            钾含量
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="bg-white divide-y divide-gray-200">
                                    {envData.map((item, index) => (
                                        <tr key={item.id} className={index % 2 === 0 ? 'bg-gray-50' : ''}>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                {formatDateTime(item.record_time)}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                {item.device_id}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.air_temp,
                                                    getCurrentThresholds().air_temp_min,
                                                    getCurrentThresholds().air_temp_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.air_temp}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.air_humidity,
                                                    getCurrentThresholds().air_humidity_min,
                                                    getCurrentThresholds().air_humidity_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.air_humidity}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.soil_temp,
                                                    getCurrentThresholds().soil_temp_min,
                                                    getCurrentThresholds().soil_temp_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.soil_temp}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.soil_humidity,
                                                    getCurrentThresholds().soil_humidity_min,
                                                    getCurrentThresholds().soil_humidity_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.soil_humidity}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.soil_ph,
                                                    getCurrentThresholds().soil_ph_min,
                                                    getCurrentThresholds().soil_ph_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.soil_ph}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.co2,
                                                    getCurrentThresholds().co2_min,
                                                    getCurrentThresholds().co2_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.co2}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.nitrogen,
                                                    getCurrentThresholds().nitrogen_min,
                                                    getCurrentThresholds().nitrogen_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.nitrogen}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.phosphorus,
                                                    getCurrentThresholds().phosphorus_min,
                                                    getCurrentThresholds().phosphorus_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.phosphorus}</span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                                <span className={`${!isValueInRange(
                                                    item.potassium,
                                                    getCurrentThresholds().potassium_min,
                                                    getCurrentThresholds().potassium_max
                                                ) ? 'text-red-500' : ''
                                                    }`}>{item.potassium}</span>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {/* 分页控制 */}
                        <div className="px-4 py-3 flex items-center justify-between border-t border-gray-200">
                            <div className="flex-1 flex justify-between sm:hidden">
                                <button
                                    className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
                                    onClick={goToPrevPage}
                                    disabled={skip === 0}
                                >
                                    上一页
                                </button>
                                <button
                                    className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
                                    onClick={goToNextPage}
                                    disabled={(skip + limit) >= totalCount}
                                >
                                    下一页
                                </button>
                            </div>
                            <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                                <div>
                                    <p className="text-sm text-gray-700">
                                        显示 <span className="font-medium">{skip + 1}</span> 到 <span className="font-medium">{Math.min(skip + limit, totalCount)}</span>
                                        条，共 <span className="font-medium">{totalCount}</span> 条
                                    </p>
                                </div>
                                <div>
                                    <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                                        <button
                                            className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                                            onClick={goToPrevPage}
                                            disabled={skip === 0}
                                        >
                                            <span className="sr-only">上一页</span>
                                            <i className="fas fa-chevron-left text-xs"></i>
                                        </button>
                                        <button
                                            className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50"
                                            onClick={goToNextPage}
                                            disabled={(skip + limit) >= totalCount}
                                        >
                                            <span className="sr-only">下一页</span>
                                            <i className="fas fa-chevron-right text-xs"></i>
                                        </button>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* 添加环境记录模态框 */}
            {isAddModalOpen && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
                        <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                            <h3 className="text-lg font-medium text-gray-900">添加环境记录数据</h3>
                            <button onClick={closeAddModal} className="text-gray-500 hover:text-gray-700">
                                <i className="fas fa-times"></i>
                            </button>
                        </div>

                        <div className="px-6 py-4">
                            {submitStatus.success ? (
                                <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded mb-4 flex items-center">
                                    <i className="fas fa-check-circle mr-2 text-green-500"></i>
                                    <p>环境记录数据添加成功！</p>
                                </div>
                            ) : submitStatus.error ? (
                                <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded mb-4 flex items-center">
                                    <i className="fas fa-exclamation-circle mr-2 text-red-500"></i>
                                    <p>{submitStatus.error}</p>
                                </div>
                            ) : null}

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">记录时间</label>
                                    <input
                                        type="datetime-local"
                                        value={formData.record_time}
                                        onChange={handleRecordTimeChange}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">设备ID</label>
                                    <select
                                        name="device_id"
                                        value={formData.device_id}
                                        onChange={handleFormChange}
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    >
                                        {FIXED_DEVICE_IDS.map(deviceId => (
                                            <option key={deviceId} value={deviceId}>
                                                设备 {deviceId}
                                            </option>
                                        ))}
                                    </select>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">空气温度(°C)</label>
                                    <input
                                        type="number"
                                        name="air_temp"
                                        value={formData.air_temp}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().air_temp_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().air_temp_min} - {getCurrentThresholds().air_temp_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">空气湿度(%)</label>
                                    <input
                                        type="number"
                                        name="air_humidity"
                                        value={formData.air_humidity}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().air_humidity_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().air_humidity_min} - {getCurrentThresholds().air_humidity_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">土壤温度(°C)</label>
                                    <input
                                        type="number"
                                        name="soil_temp"
                                        value={formData.soil_temp}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().soil_temp_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().soil_temp_min} - {getCurrentThresholds().soil_temp_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">土壤湿度(%)</label>
                                    <input
                                        type="number"
                                        name="soil_humidity"
                                        value={formData.soil_humidity}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().soil_humidity_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().soil_humidity_min} - {getCurrentThresholds().soil_humidity_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">土壤pH值</label>
                                    <input
                                        type="number"
                                        name="soil_ph"
                                        value={formData.soil_ph}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().soil_ph_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().soil_ph_min} - {getCurrentThresholds().soil_ph_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">CO2浓度(ppm)</label>
                                    <input
                                        type="number"
                                        name="co2"
                                        value={formData.co2}
                                        onChange={handleFormChange}
                                        step="1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().co2_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().co2_min} - {getCurrentThresholds().co2_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">氮含量</label>
                                    <input
                                        type="number"
                                        name="nitrogen"
                                        value={formData.nitrogen}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().nitrogen_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().nitrogen_min} - {getCurrentThresholds().nitrogen_max}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1">磷含量</label>
                                    <input
                                        type="number"
                                        name="phosphorus"
                                        value={formData.phosphorus}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().phosphorus_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().phosphorus_min} - {getCurrentThresholds().phosphorus_max}
                                        </p>
                                    )}
                                </div>

                                <div className="md:col-span-2">
                                    <label className="block text-sm font-medium text-gray-700 mb-1">钾含量</label>
                                    <input
                                        type="number"
                                        name="potassium"
                                        value={formData.potassium}
                                        onChange={handleFormChange}
                                        step="0.1"
                                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                    />
                                    {getCurrentThresholds().potassium_min !== undefined && (
                                        <p className="text-xs text-gray-500 mt-1">
                                            建议范围: {getCurrentThresholds().potassium_min} - {getCurrentThresholds().potassium_max}
                                        </p>
                                    )}
                                </div>
                            </div>
                        </div>

                        <div className="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
                            <button
                                onClick={closeAddModal}
                                className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500"
                            >
                                取消
                            </button>
                            <button
                                onClick={createEnvData}
                                disabled={submitStatus.loading}
                                className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50"
                            >
                                {submitStatus.loading ? (
                                    <span className="flex items-center">
                                        <i className="fas fa-spinner fa-spin mr-2"></i> 提交中...
                                    </span>
                                ) : (
                                    <span>提交</span>
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default EnvData;